# -*- coding: utf-8 -*-
# !/usr/bin/env python
from rest_framework.views import APIView
from components.models import ElinkHostsGroup
from components.resource_management.host_group_manage.dao import query_host_group
from utils.views import Result

class HostGroup(APIView):
    def get(self, request):
        data = request.query_params
        if data.get('env_id'): host_group_list = query_host_group(data['env_id'])
        else: host_group_list = query_host_group()

        return Result.success_response(data=host_group_list, msg='查询成功')

    def post(self, request):
        data = request.data
        if data.get('env_type_text'): data.pop('env_type_text')
        data['status'] = 1
        try:
            save_data = ElinkHostsGroup(**data)
            save_data.save()
        except Exception as e: return Result.fail_response(msg=str(e))

        return Result.success_response(msg='保存成功')


    def put(self, request):
        data = request.data.copy()

        ElinkHostsGroup.objects.filter(env_id=data['env_id']).update(
            project_id=data['project_id'],
            env_name=data['env_name'],
            env_type_code=data['env_type_code'],
            env_code=data['env_code'],
            env_ops_manage=data['env_ops_manage'],
            comment=data['comment']
        )

        return Result.success_response(msg='修改成功')


    def delete(self, request):
        data = request.data
        env_ids = data['env_ids']

        ElinkHostsGroup.objects.filter(env_id__in=env_ids).update(status=0)

        return Result.success_response(msg='删除成功')